<template>
  <AdminHeader></AdminHeader>
    <div class="admin-chapters">
      <div class="search-bar">
          <el-select v-model="searchType" placeholder="请选择搜索类型" class="search-type">
            <el-option label="书籍ID" value="1"></el-option>
          </el-select>
          <el-input v-model="searchInput" @keydown.enter="search" placeholder="请输入搜索内容" class="search-input"></el-input>
          <el-button type="primary" @click="search">搜索</el-button>
      </div>
      <el-table :data="filteredChapters.length ? filteredChapters : chapters" stripe style="width: 100%" class="chapter-table">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="chapter_novelID" label="归属书籍ID"></el-table-column>
        <el-table-column prop="novel_name" label="书名"></el-table-column>
        <el-table-column prop="chapter_title" label="章节名称"></el-table-column>
        <el-table-column prop="update_time" label="发布时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="editChapter(scope.row.id)">编辑</el-button>
            <el-button type="danger" @click="deleteChapter(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalChapters"
            class="pagination">
        </el-pagination>
      </div>
    </div>
  </template>
  
  <script lang="js">
  import { ref, onMounted } from 'vue';
  import axios from 'axios';
  import VueCookies from "vue-cookies";
  import AdminHeader from "@/components/AdminHeader.vue";
  import {ElMessageBox, ElNotification} from "element-plus";
  import router from "@/router/index.js";
  import config from "../../../config/config.js";
  
  export default {
    components: {
      AdminHeader,
    },
    setup() {
      const chapters = ref([]);
      const totalChapters = ref(0);
      const currentPage = ref(1);
      const pageSize = ref(1);
      const searchInput = ref('');
      const searchType = ref('1'); // 默认搜索类型为用户名
      const filteredChapters = ref([]);
      const adminToken = VueCookies.get('adminToken');
  
      const fetchChapters = async () => {
        try {
          const response = await axios.get(`${config.apiUrl}/admin/chapter/all?page=${currentPage.value}`, {
            headers: {
              Authorization: `Bearer ${adminToken}`
            }
          });
          chapters.value = response.data.chapters;
          totalChapters.value = response.data.totalPages * pageSize.value;
        } catch (error) {
          console.error('Error fetching chapters:', error);
        }
      };
  
      const search = () => {
        router.push('/admin/chapter/search/'+searchInput.value);
      };
  
  
      const handleSizeChange = (val) => {
        pageSize.value = val;
        fetchChapters();
      };
  
      const handleCurrentChange = (val) => {
        currentPage.value = val;
        fetchChapters();
      };
      const editChapter = (chapterId) => {
        // 编辑章节逻辑
        router.push('/admin/chapter/edit/'+chapterId);
      };
  
      const deleteChapter = async (chapterId) => {
        try {
          // 弹出确认对话框
          await ElMessageBox.confirm('确定要删除该章吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
          // 用户确认删除后执行删除操作
          const apiUrl = `${config.apiUrl}/novel-chapter/delete?chapterId=${chapterId}`;
          const response = await axios.get(apiUrl, {
            headers: {
              Authorization: `Bearer ${adminToken}`
            }
          });
          ElNotification({
            message: "删除成功！",
            type: 'success',
            duration: 1000
          });
          // 删除成功后更新用户列表数据
          if (searchInput.value) {
            await search();
          } else {
            // 否则，更新用户列表数据
            await fetchChapters();
          }
        } catch (error) {
          console.error('Error delete chapter:', error);
        }
      };
  
      onMounted(() => {
        fetchChapters();
      });
  
  
  
      return {
        chapters,
        totalChapters,
        currentPage,
        pageSize,
        searchInput,
        searchType,
        filteredChapters,
        search,
        handleSizeChange,
        handleCurrentChange,
        editChapter,
        deleteChapter,
      };
    },
  };
  </script>
  
  <style scoped>
  .admin-chapters {
    padding: 20px;
  }
  
  .search-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .search-type {
    width: 100px;
    margin-right: 10px;
  }
  
  .search-input {
    width: 80%;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    flex-wrap: wrap; /* 允许弹性项目在需要时换行 */
  }
  .pagination {
    max-width: 100%; /* 限制宽度为父容器的100% */
    overflow-x: auto; /* 如果内容超出宽度，则显示水平滚动条 */
  }
  
  .chapter-table {
    margin-top: 20px;
  }
  </style>
  